package ru.firststeps.speedtest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class SpeedMeasure extends Thread {
    public static final int MEASURE_TIME_MILlIS = 10000;
    private Handler handler;
    private boolean continueMeasuring = true;
    private static final String TAG = "SpeedMeasure";

    public SpeedMeasure(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        InputStream is = null;
        long startTime;
        long endTime;
        Bundle bundle = new Bundle();
        Message msg = handler.obtainMessage();
        Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    sleep(MEASURE_TIME_MILlIS);
                    stopMeasuring();
                } catch (InterruptedException e) {
                    Log.e(TAG, "Interrupted exception in timer thread: ", e);
                }
            }
        };
        try {
            URL url = new URL("http://firststeps.h19.ru/hawaii_poster_lrg.jpg");
            URLConnection connection = url.openConnection();
            is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            double i = 0;
            t.start();
            startTime = System.currentTimeMillis();
            while (continueMeasuring && bis.read() != -1) {
                i++;
            }
            endTime = System.currentTimeMillis();
            double speed = i / (endTime - startTime) * 1000;
            bundle.putDouble("Speed", speed);
        } catch (Exception e) {
            Log.e(TAG, "Exception during connection to url: ", e);
            bundle.putString("Error", e.getLocalizedMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e2) {
                    Log.e(TAG, "Exception during closing stream : ", e2);
                    e2.printStackTrace();
                }
            }
        }
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    private synchronized void stopMeasuring() {
        continueMeasuring = false;
    }

}
